import { Upload } from "antd";
import React, { useImperativeHandle, useState } from "react";
import PubSub from "pubsub-js";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";

export const UploadCom = React.forwardRef((props: any, ref: any) => {
  const [loading, setLoading] = useState(false);
  const uploadButton = ( 
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  let [imageUrl, setImageUrl] = useState("");
  let handleChange = (ww: any) => {
    if (ww.fileList[0].response) {
      setImageUrl(ww.fileList[0].response.headimgurl);
      // PubSub.publish("aa", imageUrl);
    }
  };

  useImperativeHandle(ref, () => {
    console.log(imageUrl);
    return {
      imageUrl,
    };
  });

  return (
    <div>
      <Upload
        name={props.name}
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action={props.action}
        method={props.method}
        onChange={handleChange}
      >
        {props.url || imageUrl?
          <img
            src={imageUrl ? imageUrl : props.url}
            alt="avatar"
            style={{ width: "100%" }}
          />
        : uploadButton}
      </Upload>
    </div>
  );
});
